package com.example.controller;

import com.example.constant.Constant;
import com.example.dto.EmpDto;
import com.example.exception.MyException;
import com.example.pojo.Emp;
import com.example.pojo.Result;
import com.example.pojo.ValidateCode;
import com.example.service.EmpService;
import com.example.service.SessionService;
import com.example.service.ValidateCodeService;
import com.example.util.JwtUtil;
import com.example.util.Md5Util;
import com.example.util.ThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.Pattern;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/emp")
@Validated
//
public class EmpController {

    @Autowired
    private EmpService empService;

    @Autowired
    private ValidateCodeService validateCodeService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private SessionService sessionService;

    /**
     * 注册
     *
     * @param username
     * @param password
     * @return
     */
//    @ApiOperation("注册")
    @PostMapping("/register")
    public Result registerEmp(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {
        Emp emp = empService.findByUsername(username);
        if (emp == null) {
            empService.register(username, password);
            return Result.success(Constant.REGISTER_SUCCESS);
        } else {
            throw new MyException(Constant.SELECT_NULL_EXCEPTION);
        }
    }

//    /**
//     * 登录
//     *
//     * @param username
//     * @param password
//     * @return
//     */
//    @PostMapping("/login")
//    public Result loginEmp(String username, String password,String captcha,String codeKey) {
//
////        String redisCode = redisTemplate.opsForValue().get("emp:login:"+codeKey);
////        if(StrUtil.isEmpty(redisCode) || !StrUtil.equals(redisCode,captcha)){
////            return Result.error("验证码错误");
////        }
////
////        redisTemplate.delete("emp:login:"+codeKey);
//
//        Emp emp = empService.findByUsername(username);
//        if (emp.getPassword().equals(Md5Util.getMD5String(password)) || emp.getPassword().equals(password)) {
//            Map<String, Object> claims = new HashMap<>();
//            claims.put("id", emp.getId());
//            claims.put("username", emp.getUsername());
//            String token = JwtUtil.genToken(claims);
//            return Result.success(token);
//        } else {
//            return Result.error("账号或密码错误");
//        }
//    }

    /*//TODO 测试
    @CrossOrigin(origins = "http://localhost:5173")
    @PostMapping("/login/test")
    public Result login(@RequestBody LoginRequest loginRequest, HttpServletResponse response, HttpServletRequest request) {
        if(loginRequest.getAccount() .equals("chengxuanfu")  && loginRequest.getPwd().equals("111111")){
            return Result.success("成功");
        }
            System.out.println("失败");
            return Result.error("");
    }*/

    /**
     * 登录通过session中的验证码进行验证
     *
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/login")
        public Result loginEmp(String username, String password,String captcha,String codeKey,HttpServletRequest request) {

        /*HttpSession session = request.getSession();
        String code  = (String) session.getAttribute("emp:login:" + codeKey);
        //TODO 验证
        if(StrUtil.isEmpty(code) || !StrUtil.equals(captcha,code)){
            return Result.error("验证码错误");
        }*/

        Emp emp = empService.findByUsername(username);
        if (emp.getPassword().equals(Md5Util.getMD5String(password)) || emp.getPassword().equals(password)) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", emp.getId());
            claims.put("username", emp.getUsername());
            //测试
            ThreadLocalUtil.set(claims);
            System.out.println(Optional.ofNullable(ThreadLocalUtil.get()));
            System.out.println(claims);
            String token = JwtUtil.genToken(claims);
            return Result.success(token);
        } else {
            return Result.error("账号或密码错误");
        }
    }

//    /**
//     * 生成验证码
//     * @return
//     */
//    @GetMapping("/generate")
//    public Result generateValidateCode(){
//        ValidateCode validateCode = validateCodeService.generateValidateCode();
//        return Result.success(validateCode);
//    }

    /**
     * 生成验证码存入session
     * @return
     */
    @GetMapping("/generate")
    public Result generateValidateCode(HttpServletRequest request){
        ValidateCode validateCode = sessionService.generateValidateCode(request);
        return Result.success(validateCode);
    }

    /**
     * 获取信息
     *
     * @return
     */
    @GetMapping("/empInfo")
    public Result GetEmpInfo() {
        //测试
        System.out.println(Optional.ofNullable(ThreadLocalUtil.get()));
        Map<String, Object> map = ThreadLocalUtil.get();
        //测试
        System.out.println("map==>"+map);
        String username = (String) map.get("username");
        //测试
        System.out.println(username);
        Emp emp = empService.findByUsername(username);
        emp.setUpdateTime(LocalDateTime.now());
        return Result.success(emp);
    }

    /**
     * 更新基本信息
     * @param empDto
     * @return
     */
    @PutMapping("/update")
    public Result updateEmpInfo(@RequestBody EmpDto empDto){
        Emp emp = new Emp();
        BeanUtils.copyProperties(empDto,emp);
        empService.updateEmpInfo(emp);
        return Result.success("更新用户基本信息");
    }

    /**
     * 更新头像
     * @param avatarUrl
     * @return
     */
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam String avatarUrl){
        empService.updateAvatar(avatarUrl);
        return Result.success("更新头像成功");
    }

    /**
     * 修改密码
     * @param map
     * @return
     */
    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String,String> map){
        String oldPwd = map.get("old_pwd");
        String newPwd = map.get("new_pwd");
        String rePwd = map.get("re_pwd");
        Map<String,Object> map1 = ThreadLocalUtil.get();
        String username = (String) map1.get("username");
        Emp emp = empService.findByUsername(username);
        if(emp.getPassword().equals(Md5Util.getMD5String(oldPwd)) || emp.getPassword().equals(oldPwd)){
            if(newPwd.equals(rePwd)){
                empService.updatePwd(rePwd);
                return Result.success("更新密码");
            }else{
                return Result.error("两次密码输入不一致");
            }
        }else{
            return Result.error("原密码输入不正确");
        }
    }
}
